import moment from 'moment'
import mongoose from '../config/DBHelpler'

const Schema = mongoose.Schema

const ContentSchema = new mongoose.Schema({
  uid: { type: String, ref: 'users' },
  title: { type: String },
  content: { type: String },
  created: { type: Date },
  catalog: { type: String },
  fav: { type: String },
  isEnd: { type: String, default: '0' },
  reads: { type: Number, default: 0 },
  answer: { type: Number, default: 0 },
  status: { type: String, default: '0' },
  isTop: { type: String, default: '0' },
  sort: { type: String, default: 100 },
  tags: {
    type: Array,
    default: [
      {
        name: '',
        class: '',
      },
    ],
  },
})

ContentSchema.post('save', function (err, doc, next) {
  if (err.name === 'MongoError' && err.code === 11000) {
    next(new Error('Error: Monngose has a duplicate key.'))
  } else {
    next(err)
  }
})

ContentSchema.statics = {
  /**
   *
   * @param {Object} options 筛选条件
   * @param {String} sort 排序方式
   * @param {Number} page 分页页数
   * @param {Number} limit 分页条数
   * @returns
   */
  getList(options, sort, page, limit) {
    return this.find(options)
      .sort({ [sort]: -1 })
      .skip(page * limit)
      .limit(limit)
      .populate({
        path: 'uid',
        select: 'name isVip pic _id', //前端返回用户主键有没有风险
      })
  },
  getHotWeek: function () {
    return this.find(
      {
        created: {
          $gte: moment().subtract(7, 'days'),
        },
      },
      {
        uid: 1,
        answer: 1,
        title: 1,
      }
    )
      .sort({
        answer: -1,
      })
      .limit(15)
  },
  findByUid: function (tid) {
    return this.findOne({ _id: tid }).populate({
      path: 'uid',
      select: 'name isVip pic _id',
    })
  },
}

const List = mongoose.model('list', ContentSchema)

export default List
